import { BYTEDANCE, WECHAT } from 'cc/env';
import { bannerwxwx } from './bannerwxwx';
// 全局单例
export class RewardedVideoAd {
  private static instance = null as unknown as RewardedVideoAd;
  private rewardedVideoAd = null;
  private rewardedVideoSuccess = false;

  private callbackObject: any = null;
  private succCallback: Function = null;
  private failCallback: Function = null;
  public static Instance() {
    if (!RewardedVideoAd.instance) {
      RewardedVideoAd.instance = new RewardedVideoAd();
    }
    return RewardedVideoAd.instance;
  }
  constructor() { }
  // 创建和展示一体化
  public create() {
    if (WECHAT || BYTEDANCE) {
      this.wxCreateAd();
    }
  }
  public show() {
    if (WECHAT || BYTEDANCE) {
      if (this.rewardedVideoAd) {
        this.rewardedVideoAd.show();
      }
    }
  }
  public hide() {}
  public destroy() {}
  public setCallback(caller: any, sussFunc: Function, failFunc: Function) {
    this.callbackObject = caller;
    this.succCallback = sussFunc;
    this.failCallback = failFunc;
  }
  private wxCreateAd() {
    const that = this;
    if (this.rewardedVideoAd) {
      if (!this.rewardedVideoSuccess) {
        this.rewardedVideoAd.load();
      }
      return;
    }
    // 创建激励视频广告实例，提前初始化
    if (WECHAT) {
      this.rewardedVideoAd = wx.createRewardedVideoAd({
        adUnitId: bannerwxwx.jilieiddd
      });
    } else if (BYTEDANCE) {
      this.rewardedVideoAd = tt.createRewardedVideoAd({
        adUnitId: 'dcm9bht8ss453d3pls'
      });
    }
    
    this.rewardedVideoSuccess = false;
    this.rewardedVideoAd.onLoad(() => {
      that.rewardedVideoSuccess = true;
    });
  
    this.rewardedVideoAd.onError((err: any) => {
      that.rewardedVideoSuccess = false;
      wx.showToast({ title: '广告加载异常', icon: 'error', duration: 3000 });
    });
    this.rewardedVideoAd.onClose((res: any) => {
      // 用户点击了【关闭广告】按钮
      // 小于 2.1.0 的基础库版本，res 是一个 undefined
      if (res && res.isEnded || res === undefined) {
        // 正常播放结束，可以下发游戏奖励
        that.succCallback.call(that.callbackObject);
      } else {
        // 播放中途退出，不下发游戏奖励
        that.failCallback.call(that.callbackObject);
      }
    });
    this.rewardedVideoAd.load();
  }
}